package com.chapter.sample.redis;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class LettuceDemo {
    public static void main(String[] args) {
        //通过构造器build出RedisURI
        RedisURI uri = RedisURI.builder()
                .redis("172.16.27.149")
                .withPort(6381)
                .withAuthentication("default", "123456")
                .build();
        //2、创建连接客户端
        RedisClient redisClient = RedisClient.create(uri);
        StatefulRedisConnection conn = redisClient.connect();

        //3、创建操作的commond
        RedisCommands commands = conn.sync();

        //==================start biz============
        //String
        List keys = commands.keys("*");
        keys.forEach(System.out::println);

        //list
        commands.lpush("mylist2", "v1", "v2", "v3");
        List list2 = commands.lrange("mylist2", 0, -1);
        list2.forEach(System.out::println);

        //set
        commands.sadd("mySet2", "v1", "v2", "v3");
        Set mySet2 = commands.smembers("mySet2");
        mySet2.forEach(System.out::println);

        //hash
        Map<String, String> map = new HashMap<>();
        map.put("k1", "138xxxxxxxx");
        map.put("k2", "beijing");
        map.put("k3", "guangzhou@163.com");
        commands.hmset("myHash2", map);
        List hmget = commands.hmget("myHash2", "k1");
        hmget.forEach(System.out::println);
        Map<String, String> myHash2 = commands.hgetall("myHash2");
        for (String key : myHash2.keySet()) {
            System.out.println("hash k= " + key + " val= " + myHash2.get(key));
        }

        //zset
        commands.zadd("myZset2", 100D, "s1", 200D, "s2", 300D, "s3");
        List myZset2 = commands.zrange("myZset2", 0, -1);
        myZset2.forEach(System.out::println);

        //==================end biz============

        //4、关闭释放资源
        conn.close();
        redisClient.shutdown();


    }
}
